package repository

import (
	"github.com/lab-online/internal/report/entity"
	"github.com/lab-online/internal/report/infra/model"
	"github.com/lab-online/internal/shared/code"
	"github.com/lab-online/pkg/util"
)

func (r *Repository) GetReportByID(reportID uint) (entity.ReportEntity, error) {
	query := model.New(model.WithID(reportID))
	if err := r.db.Joins("Content").Where(query).First(&query).Error; err != nil {
		return nil, r.errorHandler(err)
	}

	return query.ToEntity(), nil
}

func (r *Repository) GetReportByStudentAndClassIDAndExperimentID(
	student string, classID, experimentID uint,
) (entity.ReportEntity, error) {
	query := model.New(
		model.WithStudent(student),
		model.WithClassID(classID),
		model.WithExperimentID(experimentID),
	)
	if err := r.db.Joins("Content").Where(query).First(&query).Error; err != nil {
		return nil, r.errorHandler(err)
	}

	return query.ToEntity(), nil
}

func (r *Repository) SearchReport(
	reportEntity entity.ReportEntity,
) ([]entity.ReportEntity, error) {
	if reportEntity.GetID() != 0 {
		if report, err := r.GetReportByID(reportEntity.GetID()); err == nil {
			return []entity.ReportEntity{report}, nil
		} else {
			return nil, code.ErrorPicker(err, code.DatabaseReportNotFound, nil)
		}
	}

	query := model.New(model.WithEntity(reportEntity))
	var reports []*model.Report
	if err := r.db.Where(query).Find(&reports).Error; err != nil {
		return nil, r.errorHandler(err)
	}

	return util.SliceMap(reports, func(report *model.Report) entity.ReportEntity {
		return report.ToEntity()
	}), nil
}
